import 'package:flutter/material.dart';
import 'package:meal/utils/styles.dart';

class OverlayPage extends StatefulWidget {
  const OverlayPage({Key? key}) : super(key: key);

  @override
  State<OverlayPage> createState() => _OverlayPageState();
}

class _OverlayPageState extends State<OverlayPage> {
  late OverlayEntry overlayEntry;
  var width, height, overIndex;

  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }

  _itemOneGuide() {
    overIndex = 5;
    overlayEntry = OverlayEntry(builder: (context) {
      return Stack(children: [
        Positioned(
            top: (height - 200) * 0.5,
            left: (width - 200) * 0.5,
            child: GestureDetector(
                onTap: () => overlayEntry.remove(),
                child: _itemContainer(Colors.blue.withOpacity(0.6))))
      ]);
    });
    Overlay.of(context).insert(overlayEntry);
  }

  Widget _itemContainer(Color withOpacity) {
    return Container(
      alignment: Alignment.center,
      child: Text(
        '居中Overlay',
        style: StylesUtils.defaultTextStyle(),
      ),
    );
  }
}

class SimpleOverlayPage extends StatefulWidget {
  const SimpleOverlayPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _SimpleOverlayPageState();
  }
}

class _SimpleOverlayPageState extends State<SimpleOverlayPage> {
  final GlobalKey _noticeKey = GlobalKey();
  OverlayEntry? _overlayEntry;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Overlay+OverlayEntry"),
        actions: [
          Padding(
            key: _noticeKey,
            padding: const EdgeInsets.all(16),
            child: const Icon(Icons.notifications),
          )
        ],
      ),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text("该示例在AppBar右上角的图标出显示一个提示信息"),
            TextButton(
              onPressed: () {
                showOverlay(context);
              },
              child: const Text(
                "show icon",
                style: TextStyle(
                  fontSize: 30,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///显示浮层
  void showOverlay(BuildContext context) async {
    if (_overlayEntry != null) {
      _overlayEntry?.remove();
      _overlayEntry = null;
      return;
    }
    //1、获取OverlayState
    OverlayState overlayState = Overlay.of(context);
    //2、创建OverlayEntry
    _overlayEntry = OverlayEntry(
      builder: (ctx) {
        //获取_noticeKey Widget的位置，用于设置OverlayEntry将悬浮的位置
        RenderBox? renderBox = _noticeKey.currentContext?.findRenderObject() as RenderBox?;
        Size size = renderBox?.size ?? Size.zero;
        Offset offset = renderBox?.localToGlobal(Offset.zero) ?? Offset.zero;
        final double top = offset.dy + size.height;
        double radius = 20.0;
        double right = offset.dx + size.width / 2 - radius;
        return Positioned(
          top: top,
          left: right,
          child: CircleAvatar(
            radius: radius,
            backgroundColor: Colors.orange,
            child: const Text('20'),
          ),
        );
      },
      opaque: false,
    );

    //3、将OverlayEntry插入到Overlay中。
    overlayState.insert(_overlayEntry!);
  }
}

///实现类似PopupWindow的弹窗效果
class PopupDialogPage extends StatefulWidget {
  const PopupDialogPage({Key? key}) : super(key: key);

  @override
  _PopupDialogPageState createState() {
    return _PopupDialogPageState();
  }
}

class _PopupDialogPageState extends State<PopupDialogPage> {
  final GlobalKey nameKey = GlobalKey();
  final TextEditingController _controller = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  OverlayEntry? _overlayEntry;
  final LayerLink _layerLink = LayerLink();

  // FollowerLayer followerLayer = FollowerLayer(link: _layerLink);

  @override
  void initState() {
    super.initState();
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
        showOverlay(context);
      } else {
        dismissOverlay();
      }
    });
  }

  @override
  void dispose() {
    // _focusNode.removeListener(() { })
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Overlay"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              height: 60,
              color: Colors.orange,
            ),
            Container(
              height: 40,
              color: Colors.yellow,
              child: const Text("在输入框下显示可以输入的用户名"),
            ),
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 30),
              child: CompositedTransformTarget(
                // link: LayerLink(),
                link: _layerLink,
                child: TextField(
                  key: nameKey,
                  focusNode: _focusNode,
                  controller: _controller,
                  decoration: InputDecoration(
                    label: const Text("输入用户名"),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                ),
              ),
            ),
            Container(
              height: 100,
              color: Colors.green,
            ),
          ],
        ),
      ),
    );
  }

  void showOverlay(BuildContext context) {
    final overlay = Overlay.of(context);
    _overlayEntry = OverlayEntry(builder: (ctx) {
      final renderBox = nameKey.currentContext?.findRenderObject() as RenderBox;
      final size = renderBox.size;
      // final offset = renderBox.localToGlobal(Offset.zero);

      ///如果使用了CompositedTransformFollower,就不在在对Positioned 设置left,top
      return Positioned(
        // left: offset.dx,
        // top: offset.dy + size.height,
        width: size.width,
        child: CompositedTransformFollower(
          link: _layerLink,
          showWhenUnlinked: false,
          offset: Offset(0, size.height + 8),
          child: Material(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                ListTile(
                  title: Text("ZhangSan"),
                  subtitle: Text("CFO"),
                  onTap: () {
                    _controller.text = "ZhangSan";
                    dismissOverlay();
                    _focusNode.unfocus();
                  },
                ),
                ListTile(
                  title: Text("HuShuo"),
                  subtitle: Text("CEO"),
                  onTap: () {
                    _controller.text = "HuShuo";
                    dismissOverlay();
                    _focusNode.unfocus();
                  },
                ),
                ListTile(
                  title: Text("LiMing"),
                  subtitle: Text("Common"),
                  onTap: () {
                    _controller.text = "LiMing";
                    dismissOverlay();
                    _focusNode.unfocus();
                  },
                ),
              ],
            ),
          ),
        ),
      );
    });
    overlay.insert(_overlayEntry!);
  }

  void dismissOverlay() {
    if (_overlayEntry != null) {
      _overlayEntry?.remove();
      _overlayEntry = null;
    }
  }
}
